package cn.car.interceptor;

import cn.car.annotation.PassToken;
import cn.car.exception.BusinessException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JwtInterceptor implements HandlerInterceptor {

    private static final String SECRET_KEY = "zys";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查是否有PassToken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 从请求头中获取token
        String token = request.getHeader("token");

        // 验证token
        if (token == null || !JWTUtil.verify(token, SECRET_KEY.getBytes())) {
            throw new BusinessException(401, "无效的token");
        }

        // 验证token是否过期
//        JWT jwt = JWTUtil.parseToken(token);
//        if (!jwt.validate(0)) {
//            throw new BusinessException(401, "token已过期");
//        }

        return true;
    }
}
